package com.wsp.controllermanagement.execption;

import com.wsp.apimanagement.pojo.dto.Result;
import com.wsp.apimanagement.util.CommonResultBuilderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Package: com.wsp.controllermanagement.execption
 * Description： TODO
 *
 * @Author: 巫思平
 * Copyright: Copyright (c) 2020
 * Version: 1
 */
@Slf4j
@ControllerAdvice(basePackages = "com.wsp.controllermanagement.controller")
public class CommonExceptionHandler {
    /**
     * 空参或参数类型错误异常
     */
    @ExceptionHandler({MissingServletRequestParameterException.class,TypeMismatchException.class})
    @ResponseBody
    public Result<?> parameterExceptionHandler(Exception ex) {
        if(ex instanceof TypeMismatchException) {
            TypeMismatchException e = (TypeMismatchException)ex;
            return CommonResultBuilderUtil.commonError(e.getPropertyName()+":"+e.getValue()+" 错误");
        }
        if(ex instanceof MissingServletRequestParameterException) {
            MissingServletRequestParameterException e = (MissingServletRequestParameterException) ex;
            return CommonResultBuilderUtil.commonError(e.getParameterName()+":参数确实");
        }
        return CommonResultBuilderUtil.commonError("拒绝服务");
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result<String> validationExceptionHandler(BindException bex) {
        final FieldError fieldError = bex.getBindingResult().getFieldError();
        if(fieldError==null) {
            return CommonResultBuilderUtil.commonError("网络异常");
        }
        return Result.<String>builder().code(400).msg(fieldError.getField()+":"+fieldError.getDefaultMessage()).data(fieldError.getField()+":"+fieldError.getDefaultMessage()).build();
    }


    @ExceptionHandler(CommonException.class)
    public Result<?> commonExceptionHandler(CommonException cex){
        log.info(cex.getMessage());
        return CommonResultBuilderUtil.commonError("网络异常");
    }
}
